package com.yanqu.road.server.manager.activity.xingyou.inter.grid;

import com.yanqu.road.entity.activity.youxing.*;
import com.yanqu.road.entity.activity.youxing.config.XingYouShanShuiGridInfo;
import com.yanqu.road.entity.log.cross.xingyou.LogCrossXingYouSlive;
import com.yanqu.road.entity.log.cross.xingyou.LogCrossXingYouWishProcess;
import com.yanqu.road.pb.activity.XingYouShanShuiProto;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.activity.commonteam.CommonTeam;
import com.yanqu.road.server.manager.activity.commonteam.CommonTeamActivity;
import com.yanqu.road.server.manager.activity.commonteam.CommonTeamMgr;
import com.yanqu.road.server.manager.activity.xingyou.ConfirmHandleResult;
import com.yanqu.road.server.manager.activity.xingyou.CrossXingYouShanShuiMgr;
import com.yanqu.road.server.manager.activity.xingyou.DiceHandleResult;
import com.yanqu.road.server.manager.activity.xingyou.enums.eXingYouGridTypes;
import com.yanqu.road.server.manager.activity.xingyou.inter.GridHandleResult;
import com.yanqu.road.server.manager.activity.xingyou.inter.IXingYouGridHandler;
import com.yanqu.road.server.manager.activity.xingyou.task.CrossXingYouSendWishShareRewardTask;
import com.yanqu.road.server.manager.log.CrossAutoLogMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

import java.util.*;

/**
 * 香火祈愿
 */
public class WishGridHandler implements IXingYouGridHandler {

    @Override
    public void handle(XingYouShanShuiGridInfo gridInfo, int pos, int gridId, int endPos, boolean fly, DiceHandleResult result) {
        //是否停留
        boolean stop = pos == endPos;
        if(!stop){
            return;
        }

        Property fixedReward = result.getActivity().getGridInfoFixedReward(result.getUserData(), gridInfo, true);

        //如果是漂泊模式
        if(result.getUserData().isDrift()){
            //空白格子
            ShanShuiGridParam gridParam = new ShanShuiGridParam(gridId, pos, true, true);
            gridParam.setDrift(true);
            GridHandleResult gridHandleResult = new GridHandleResult();
            gridHandleResult.setGridParam(gridParam);

            XingYouShanShuiProto.ShanShuiEventInfo.Builder builder = XingYouShanShuiProto.ShanShuiEventInfo.newBuilder();
            builder.setPosition(pos);
            builder.setGridId(gridId);
            builder.setIsDrift(true);
            builder.setFixedReward(PropertyHelper.parsePropertyToString(fixedReward));
            builder.setBaseReward(PropertyHelper.parsePropertyToString(fixedReward));
            builder.setAward(PropertyHelper.parsePropertyToString(fixedReward));
            gridHandleResult.setBuilder(builder);

            result.getGridHandleResultList().add(gridHandleResult);
            return;
        }

        XingYouShanShuiProto.ShanShuiEventInfo.Builder builder = XingYouShanShuiProto.ShanShuiEventInfo.newBuilder();
        GridHandleResult gridHandleResult = new GridHandleResult();
        ShanShuiGridParam gridParam = new ShanShuiGridParam(gridId, pos, false, false);
        gridHandleResult.setGridParam(gridParam);
        builder.setBaseReward(PropertyHelper.parsePropertyToString(fixedReward));
        result.getActivity().calRewardBuff(result.getUserData(), fixedReward, false, 0);

        builder.setPosition(pos);
        builder.setGridId(gridId);
        builder.setIsDrift(false);
        builder.setFixedReward(PropertyHelper.parsePropertyToString(fixedReward));
        builder.setAward(PropertyHelper.parsePropertyToString(fixedReward));
        gridHandleResult.setBuilder(builder);
        result.getGridHandleResultList().add(gridHandleResult);
    }


    @Override
    public void confirm(XingYouShanShuiGridInfo gridInfo, CrossXingYouShanShuiUserData userData, ConfirmHandleResult handleResult, long select, boolean isDrift) {

        if(gridInfo.getId() != 13){
            handleResult.setRet(GameErrorCode.E_REQUEST_ARGUMENT_ERROR);
            return;
        }
        if(userData.isDrift()){
            return;
        }
        CrossXingYouShanShuiTeamData teamData = handleResult.getActivity().getTeamData(userData.getTeamId());
        CommonTeamActivity activity = CommonTeamMgr.getActivity(handleResult.getActivity().getConfig().getActivityInfo().getActivityId(), userData.getGroupId());
        CommonTeam team = activity.getTeam(userData.getTeamId());
        if(team == null){
            return;
        }
        XingYouShanShuiProto.ShanShuiBigWishNotify.Builder wishNotifyBuilder = null;
        synchronized (handleResult.getActivity().getTeamLocker(userData.getTeamId())){
            //本次操作进度
            int process = (int)select;
            //本次操作进度上限
            int limit = gridInfo.getParam().get(1);
            int perCost = gridInfo.getParam().get(0);

            int curWishValue = teamData.getWishValue();
            int curRound = teamData.getWishRound();

            if(curRound <= gridInfo.getParam().get(8)){
                //小佛配置
                limit = gridInfo.getParam().get(5);
                perCost = gridInfo.getParam().get(4);
            }

            //妈祖有多次数上限
            if(handleResult.getActivity().inMazuTemp(userData)){
                XingYouShanShuiGridInfo mazuGridInfo = handleResult.getActivity().getConfig().getGridInfo(eXingYouGridTypes.Fifteen.getId());
                if(mazuGridInfo != null){
                    limit = mazuGridInfo.getParam().get(1);
                }
            }

            //限制超100
            if(handleResult.isEventTouch()){
                if(teamData.getWishValue() + process > 100){
                    //本次上限
                    handleResult.setRet(GameErrorCode.E_XING_YOU_SHAN_SHUI_WISH_PROCESS_LIMIT);
                    return;
                }
            }else {
                if(userData.getGridParam().getBuy() + process > limit || teamData.getWishValue() + process > 100){
                    //本次上限
                    handleResult.setRet(GameErrorCode.E_XING_YOU_SHAN_SHUI_WISH_PROCESS_LIMIT);
                    return;
                }
            }

            int need = 0;
            if(!handleResult.isEventTouch()) {
                need = process * perCost;
                if (need > teamData.getSilverCoin()) {
                    //银币不足
                    handleResult.setRet(GameErrorCode.E_XING_YOU_SHAN_SHUI_SILVER_NO_ENOUGH);
                    return;
                }

                teamData.setSilverCoin(teamData.getSilverCoin() - need);
                //日志
                LogCrossXingYouSlive logCrossXingYouSlive = new LogCrossXingYouSlive(teamData.getTeamId(), teamData.getActivityId(), userData.getUserId(), 2, need, teamData.getSilverCoin(), 4);
                logCrossXingYouSlive.setGroupId(userData.getGroupId());
                CrossAutoLogMgr.add(logCrossXingYouSlive);
            }

            userData.getGridParam().setBuy(userData.getGridParam().getBuy() + process);
            userData.getGridParam().setHandled(true);

            //加进度
            teamData.setWishValue(process + teamData.getWishValue());

            //祈愿奖励
            int rewardCount = getAddSum(gridInfo, curRound, process, 0);

            if(teamData.getWishValue() >= 100){
                teamData.setWishRound(1 + teamData.getWishRound());
                teamData.setWishValue(teamData.getWishValue() - 100);

                //轮次奖励
                CrossXingYouShanShuiWishRewardData rewardData = new CrossXingYouShanShuiWishRewardData();
                rewardData.setGroupId(teamData.getGroupId());
                rewardData.setActivityId(handleResult.getActivity().getConfig().getActivityInfo().getActivityId());
                rewardData.setRound(curRound);
                rewardData.setTeamId(userData.getTeamId());
                rewardData.setRewardMap(new HashMap<>());
                rewardData.setInsertOption();
                handleResult.getActivity().addCrossXingYouShanShuiWishRewardData(rewardData);

                //祈愿赐福跑马灯
                teamData.setBigWishTimes(1 + teamData.getBigWishTimes());
                wishNotifyBuilder = XingYouShanShuiProto.ShanShuiBigWishNotify.newBuilder();
                wishNotifyBuilder.setBigTimes(teamData.getBigWishTimes());
                wishNotifyBuilder.setTeamName(team.getTeamName());

                //祈愿-队伍日志
                CrossXingYouShanShuiTeamActionLogData actionLogData = handleResult.getActivity().createActionLogData(userData, XingYouShanShuiProto.ShanShuiLogTypeEnum.SHAN_SHUI_LOG_TRADE_SHIP_SET_SAIL,
                        handleResult.getActivity().getConfig().getSHANSHUI_GOLD_COIN_ID() + "=" + rewardCount,
                        Arrays.asList(String.valueOf(userData.getRoleId()), handleResult.getActivity().getConfig().getSHANSHUI_SILVER_COIN_ID() + "=" + need,
                                String.valueOf(curWishValue), String.valueOf(teamData.getWishValue() + 100)));
                handleResult.getActionLogDataList().add(actionLogData);

                LogCrossXingYouWishProcess logData = new LogCrossXingYouWishProcess(userData.getActivityId(), userData.getTeamId(), userData.getUserId(),
                        curRound, need, process, teamData.getWishValue() + 100, rewardCount);
                logData.setGroupId(userData.getGroupId());
                handleResult.getAutoLogList().add(logData);

                handleResult.getActivity().getNeedSyncRedDotTeamMap().add(userData.getTeamId());

            }else {
                //祈愿-队伍日志
                CrossXingYouShanShuiTeamActionLogData actionLogData = handleResult.getActivity().createActionLogData(userData, XingYouShanShuiProto.ShanShuiLogTypeEnum.SHAN_SHUI_LOG_TRADE_SHIP_LOAD,
                        handleResult.getActivity().getConfig().getSHANSHUI_GOLD_COIN_ID() + "=" + rewardCount,
                        Arrays.asList(String.valueOf(userData.getRoleId()), handleResult.getActivity().getConfig().getSHANSHUI_SILVER_COIN_ID() + "=" + need,
                                String.valueOf(curWishValue), String.valueOf(teamData.getWishValue())));
                handleResult.getActionLogDataList().add(actionLogData);

                LogCrossXingYouWishProcess logData = new LogCrossXingYouWishProcess(userData.getActivityId(), userData.getTeamId(), userData.getUserId(),
                        curRound, need, process, teamData.getWishValue(), rewardCount);
                logData.setGroupId(userData.getGroupId());
                handleResult.getAutoLogList().add(logData);
            }

            //只给队友加奖励(事件触发的不给奖励)
            if(!handleResult.isEventTouch()) {

                handleResult.getReward().addProperty(handleResult.getActivity().getConfig().getSHANSHUI_GOLD_COIN_ID(), rewardCount);

                CrossXingYouShanShuiMgr.getThreadPool().addTask(0, new CrossXingYouSendWishShareRewardTask(userData.getUserId(), userData.getTeamId(),
                        new ArrayList<>(team.getMemberDataMap().values()), PropertyHelper.parseStringToProperty(handleResult.getActivity().getConfig().getSHANSHUI_GOLD_COIN_ID() + "="+ rewardCount), handleResult.getActivity()));
            }
        }

        if(wishNotifyBuilder != null){
            //如果是大佛，跑马灯
            for (Long uid : handleResult.getActivity().getInMapUserSet()) {
                MessageHelper.sendPacket(Protocol.U_XING_YOU_SHAN_SHUI_BIG_WISH_NOTIFY, wishNotifyBuilder, uid);
            }

            //活动聊天频道聊天频道分享
//            WorldMessageProto.WorldMessageTempMsg.Builder messageTempMsg = WorldMessageProto.WorldMessageTempMsg.newBuilder();
//            messageTempMsg.setType(eMessageType.XingYouShanShuiWish.getValue());
//            messageTempMsg.setContentType(eChatContentType.Common.getContentType());
//            messageTempMsg.setUserId(userData.getUserId());
//            messageTempMsg.setContent("");
//            messageTempMsg.setSendTime(System.currentTimeMillis() / 1000);
//            CrossUserBaseInfo userBaseInfo = CrossUserMgr.getCrossUserBaseInfo(userData.getUserId());
//            if (userBaseInfo != null && userBaseInfo.getUserBaseInfo() != null) {
//                PlayerProto.PlayerBaseTempMsg.Builder baseMsg = PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo.getUserBaseInfo());
//                messageTempMsg.setPlayerBaseData(baseMsg);
//            }
//            Map<String, Object> params = new HashMap<>();
//            params.put("type", 7);
//            params.put("teamName", wishNotifyBuilder.getTeamName());
//            params.put("times", wishNotifyBuilder.getBigTimes());
//            messageTempMsg.setExtraParams(JSON.toJSONString(params));
//            ActivityChatMgr.activityChat(handleResult.getActivity().getConfig().getActivityInfo().getActivityId(), messageTempMsg.build());
        }

        handleResult.getActivity().syncShanShuiPropNotify(userData.getTeamId(), Arrays.asList(XingYouShanShuiProto.PROP.QI_YUAN_PROGRESS_VALUE, XingYouShanShuiProto.PROP.TEAM_SILVER_VALUE, XingYouShanShuiProto.PROP.TEAM_CUL_SILVER_VALUE));

        //队伍聊天频道分享
//        CommonTeamProto.CommonTeamChatMsg.Builder chatMsgBuilder = activity.createTeamChatMsg(userData.getUserId(), CommonTeamProto.CommonTeamChatTypeEnum.ACTIVITY_VALUE, eChatContentType.Common.getContentType(), "");
//        Map<String, Object> params = new HashMap<>();
//        params.put("type", 5);
//        params.put("time", System.currentTimeMillis());
//        chatMsgBuilder.setExtraParams(JSON.toJSONString(params));
//        team.sendTeamChatMsg(chatMsgBuilder.build());

    }

    private int getAddSum(XingYouShanShuiGridInfo gridInfo, int curRound, int process, int addSum) {
        int total = addSum;
        for (int i = 0; i < process; i++) {
            int randomA = gridInfo.getParam().get(2);
            int randomB = gridInfo.getParam().get(3);
            if (curRound <= gridInfo.getParam().get(8)) {
                randomA = gridInfo.getParam().get(6);
                randomB = gridInfo.getParam().get(7);
            }

            int addPer = randomA;
            if (randomB > randomA) {
                addPer += new Random().nextInt(randomB - randomA + 1);
            }
            total += addPer;
        }
        return total;
    }
}
